package top.hmtools.jsCss.yui;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.yahoo.platform.yui.compressor.CssCompressor;

@Component
public class CssCompressorComponet {

	private final Logger logger = LoggerFactory.getLogger(CssCompressorComponet.class);
	
	/**
	 * 进行css压缩
	 * @param reader	css文本内容输入流
	 * @param writer	css文本内容输出流
	 * @param linebreak		指定列插入换行符，-1 为不插入换行符
	 */
	public void compressor(Reader reader,Writer writer,int linebreak){
		//实例化css压缩工具
		CssCompressor compressor;
		try {
			compressor = new CssCompressor(reader);
			
			//进行压缩
			compressor.compress(writer, linebreak);
		} catch (IOException e) {
			this.logger.error("压缩css时发生异常：{}",e);
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * 进行css压缩
	 * @param readerStr  css文本内容输入
	 * @param linebreak  指定列插入换行符，-1 为不插入换行符
	 * @param charset  字符编码，缺省 utf-8
	 * @return
	 */
	public String compressor(String readerStr,int linebreak,String charset){
		if(readerStr == null || readerStr.trim().length()<1){
			return null;
		}
		if(charset == null || charset.trim().length()<1){
			charset = "UTF-8";
		}
		try {
			InputStream inputStream = IOUtils.toInputStream(readerStr,charset);
			Reader reader = new InputStreamReader(inputStream, charset);
			
			StringWriter writer = new StringWriter();
			this.compressor(reader, writer, linebreak);
			return writer.toString();
		} catch (IOException e) {
			this.logger.error("压缩css时发生异常：{}",e);
			throw new RuntimeException(e.getMessage());
		}catch (IndexOutOfBoundsException e){
			return readerStr;
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
